package cn.ycc1.myupper.model;

import com.alibaba.cloud.ai.dashscope.api.DashScopeResponseFormat;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

/**
 * @author ycc
 * @date 2025/4/29
 */
@RestController
public class DashScopeChatModelController {
    private static final String DEFAULT_PROMPT = "9.8与9.11谁大？";
    private final ChatModel dashScopeChatModel;

    public DashScopeChatModelController(ChatModel chatModel) {
        this.dashScopeChatModel = chatModel;
    }

    @GetMapping("/v2/simple/chat")
    public String simpleChat() {

//        return dashScopeChatModel.call(new Prompt(DEFAULT_PROMPT)).getResult().getOutput().getContent();
        return dashScopeChatModel.call(new Prompt(DEFAULT_PROMPT)).getResult().getOutput().getText();
    }

    /**
     * Stream 流式调用。可以使大模型的输出信息实现打字机效果。
     * @return Flux<String> types.
     */
    @GetMapping("/v2/stream/chat")
    public Flux<String> streamChat(HttpServletResponse response) {

        // 避免返回乱码
        response.setCharacterEncoding("UTF-8");

        Flux<ChatResponse> stream = dashScopeChatModel.stream(new Prompt(DEFAULT_PROMPT));
        return stream.map(resp -> resp.getResult().getOutput().toString());
    }

    /**
     * 动态设置 DashScope Options
     * @return
     */
    @GetMapping("/v2/custom/chat")
    public String customChat() {

        DashScopeChatOptions customOptions = DashScopeChatOptions.builder()
                .withTopP(0.7)
                .withTopK(50)
                .withTemperature(0.8)
                .withModel("xxx")
                .build();

        return dashScopeChatModel.call(new Prompt(DEFAULT_PROMPT, customOptions)).getResult().getOutput().getText();
    }
    /**
     * 结构化返回
     * 在模型请求中，您可以指定模型的返回格式。使模型返回您需要的数据格式。
     *
     * 目前支持的输出格式为：TEXT 和 JSON_OBJECT。
     */
//    public XXXontroller(ChatModel chatModel) {
//
//        DashScopeResponseFormat responseFormat = new DashScopeResponseFormat();
//        responseFormat.setType(DashScopeResponseFormat.Type.JSON_OBJECT);
//
//        this.chatModel = chatModel;
//        this.dashScopeChatClient = ChatClient.builder(chatModel)
//                .defaultOptions(
//                        DashScopeChatOptions.builder()
//                                .withTopP(0.7)
//                                .withResponseFormat(responseFormat)
//                                .build()
//                )
//                .build();
//    }

}
